<template>
    <div class="VersionBeitie">
        <el-card class="box-card">
            <div class="header">
                <div>
                    <el-button type="primary" @click="form.adddialogVisible = true">新增</el-button>
                    <el-button :disabled="multipleSelection.length == 0" @click="isDelete()">删除</el-button>
                </div>
                <div class="right">
                    <div class="inputs">
                        <el-input style="max-width: 200px;" v-model="word" placeholder="请输入关键字" clearable
                            @clear="getList()" />
                    </div>
                    <div>
                        <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
                        <el-button :icon="RefreshRight" @click="resetPage">重置</el-button>
                    </div>
                </div>
            </div>
            <div class="main">
                <el-table stripe height="100%" ref="multipleTableRef" :data="tableData" style="width: 100%"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" />
                    <el-table-column label="版本缩略图" width="120" align="center">
                        <template #default="scope">
                            <div style="margin: 5px;">
                                <el-image :preview-src-list="[scope.row.img]"
                                    style=" width: 60px; height: 60px;border-radius: 5px;" :src="scope.row.img"
                                    :zoom-rate="1.2" :initial-index="4" fit="cover" />
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column property="name" label="作品名称" width="200" align="center" />
                    <el-table-column label="创建时间">
                        <template #default="scope"><span style="color:#767676;font-size: 14px;">{{
                            formatDate(new Date(scope.row.newDate).getTime()) }}</span></template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="300">
                        <template #default="scope">
                            <el-button link type="primary" size="small" @click="editHandle(scope.row)">编辑</el-button>
                            <el-button link type="success" size="small" @click="checkDetail(scope.row)">详情</el-button>

                            <el-popconfirm confirm-button-text="Yes" cancel-button-text="No" :icon="InfoFilled"
                                icon-color="#626AEF" title="确定删除吗？" @confirm="confirmEvent(scope.row.id)"
                                @cancel="cancelEvent">
                                <template #reference>
                                    <el-button link type="danger" size="small">删除</el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="footer">
                <div></div>
                <el-pagination v-model:current-page="pageform.pnum" v-model:page-size="pageform.psize"
                    :page-sizes="[100, 200, 300, 400]" :small="pageform.small" :disabled="pageform.disabled"
                    :background="pageform.background" layout="prev, pager, next, jumper" :total="pageform.total"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
            </div>
        </el-card>
        <!-- 添加对话框 -->
        <el-dialog v-model="form.adddialogVisible" title="新增" width="50%" :before-close="handleClose">
            <div>
                <el-form ref="ruleFormRef" :model="form.addform" :rules="form.rules" label-width="120px"
                    class="demo-ruleForm" status-icon>
                    <el-form-item label="封面图" prop="img">
                        <el-upload class="avatar-uploader" action="/dev-api/api/uploadimg/"
                            :show-file-list="false" :on-success="handleAvatarSuccess">
                            <img v-if="form.addform.img" :src="form.addform.img" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="名称" prop="name">
                        <el-input v-model="form.addform.name" />
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="form.adddialogVisible = false">
                            取消
                        </el-button>
                        <el-button type="primary" @click="submitForm(ruleFormRef)">
                            保存
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>
        <!-- 编辑对话框 -->
        <el-dialog v-model="form.editDialogVisible" title="新增" width="50%"
            :before-close="() => { form.editDialogVisible = false }">
            <div>
                <el-form ref="ruleFormRef" :model="form.editform" :rules="form.rules" label-width="120px"
                    class="demo-ruleForm" status-icon>
                    <el-form-item label="图片" prop="img">
                        <el-upload class="avatar-uploader" action="/dev-api/api/uploadimg/" :show-file-list="false"
                            :on-success="EdithandleAvatarSuccess">
                            <img v-if="form.editform.img" :src="form.editform.img" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="作品名称" prop="name">
                        <el-input v-model="form.editform.name" />
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="form.editDialogVisible = false">
                            取消
                        </el-button>
                        <el-button type="primary" @click="EditsubmitForm(ruleFormRef)">
                            保存
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
            <!-- 是否批量删除对话框-->
        </el-dialog>
        <el-dialog v-model="form.delallDialogvisible" title="删除" width="30%" center>
            <span>
                您确定要删除这些数据吗？
            </span>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="form.delallDialogvisible = false">取消</el-button>
                    <el-button type="primary" @click="allDelete()">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { ElTable, FormInstance, UploadProps } from 'element-plus'
import { Search, RefreshRight, Plus, InfoFilled } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import request from '../../utils/request'
import timeobj from './formatTime'
import './assets/global.css'
let { formatDate, formatSeconds } = timeobj//取出方法
let route = useRoute()
let router = useRouter()
let word = ref("")//模糊关键字
const tableData = ref<StoneInscription[]>([])
let vid:any = ref("")
interface StoneInscription {
    img: any
    name: string
    newDate: string
    is_delete: boolean
    id: number
}
//
const ruleFormRef = ref<FormInstance>()
let form:any = reactive({
    adddialogVisible: false,
    editDialogVisible: false,
    delallDialogvisible: false,
    addform: { name: "", img: "" },
    editform: {
        id:"",
        img: "",
        name: "",
    },
    rules: {
        name: [
            { required: true, message: '请输入作品名称', trigger: 'blur' },
            { min: 3, max: 25, message: '长度是3-25', trigger: 'blur' },
        ],
        img: [
            { required: true, message: '请上传图片信息', trigger: 'blur' },
        ],
    }
})
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<StoneInscription[]>([])
const handleSelectionChange = (val: StoneInscription[]) => {
    multipleSelection.value = val
}
// 获取数据列表 //这里是要从 route 的 query 取出 _id然后 再向后端发送请求的
let getList = async () => {
    let { id } = route.query
    vid.value = id
    // 我这里直接请求json，可以拼接上_id
    let data: any = await request.get(`/api/tabletworks/TabletEditionList/${word.value == "" ? " " : word.value}/${id}/${pageform.pnum}`)
    tableData.value = [...data.data]
    pageform.total = data.total
}
//分页选项
let pageform = reactive({
    psize: 10,
    pnum: 1,
    small: true,
    background: true,
    disabled: false,
    total: 0
})
//编辑图片上传钩子函数
const EdithandleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    // form.addform.img = URL.createObjectURL(uploadFile.raw!)
    form.editform.img = response.path
}
//分页监听函数
let handleSizeChange = (val: number) => {
    pageform.psize = val
    getList()
}
//分页监听函数
let handleCurrentChange = (val: number) => {
    pageform.pnum = val
    getList()
}
// 查看详情跳转到 碑帖版本详情
let checkDetail = (row: any) => {
    let { id } = row;
    // 版本页面根据 id 来查看 当前的碑帖的 所有版本信息
    router.push(`/stoneInscription/versionDetail?id=${id}`)
}
//关闭对话框
let handleClose = () => { form.adddialogVisible = false; form.editDialogVisible = false, form.delallDialogvisible = false }
//添加文件上传的函数
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    form.addform.img = response.path
}
// 添加确定
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            let data: any = await request.post(`/api/tabletworks/TabletEditionAdd/${vid.value}`, {
                name: form.addform.name,
                img: form.addform.img,
            })
            ElMessage.info(data.msg)
            form.adddialogVisible = false;
            form.addform = {}
            getList()
        } else {
            ElMessage.info("请完善版本信息")
        }
    })
}
// 删除气泡取消
const cancelEvent = () => {
    ElMessage.info("取消成功")
}
// 单个删除
const confirmEvent = async (id: any) => {
    let data: any = await request.delete(`/api/tabletworks/TabletEditionDel/${id}`)
    ElMessage.info(data.msg)
    getList()
}
// 重置页面操作
let resetPage = () => {
    word.value = ""
    getList()
}
//编辑
let editHandle = (row: any) => {
    // 通过id获取单个碑帖
    form.editDialogVisible = true
    form.editform = row;
}
//确认编辑
let EditsubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            let data: any = await request.put(`/api/tabletworks/TabletEditionUpd/${form.editform.id}`, {
                name: form.editform.name,
                img: form.editform.img,
            })
            ElMessage.info(data.msg)
            getList()
            form.editDialogVisible = false;
        } else {
            ElMessage.error("请完善当前作品版本信息")
        }
    })
}
//全部删除功能
let isDelete = async () => { form.delallDialogvisible = true }
// 全部删除确定
let allDelete = async () => {
    let val = []
    for (const item of multipleSelection.value) {
        val.push({ id: item.id, is_delete: 1 })
    }
    let data: any = await request.post(`/api/tabletworks/TabletEditionDelall`, val)
    ElMessage.info(data.msg)
    form.delallDialogvisible = false;
    getList()
}
onMounted(() => {
    getList()
})
</script>

<style lang="scss" scoped>
.VersionBeitie {
    width: 100%;
    height: 100%;
    min-width: 950px;
}
:deep(.el-table__row) {
    text-align: center !important;
    color: #737373;
    font-size: 15px;
}
// 表头行高背景
:deep(.el-table__header) {
    line-height: 50px;
    background-color: #f2f2f2;
    // border: 1px solid #eaeaea;
    font-size: 15px;
    font-weight: 500;
}
// 表项border
:deep(.el-table__row) {
    border: 1px solid #eaeaea;
    border-collapse: collapse;
}
// 表项 斑马色
:deep(.el-table__row:nth-child(even)) {
    background-color: #f5f5f5;
}
// 播放激活
// 解决image 全局蒙版权重的问题
:deep(.el-table .el-table__cell) {
    z-index: auto !important;
}
</style>
<!-- // 上传文件样式 -->
<style>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>